package Java7_Concurrency_Cookbook.concurrent_custom.custom_priority_transfer_queue;

import java.util.concurrent.TimeUnit;

/**
 * <b>实现基于优先级的传输队列</b><br/>
 * 本示例自定义实现了MyPriorityTransferQueue, 其具有如下特色:<br/>
 * 通过MyPriorityTransferQueue.put()方法放入其中的元素会按照优先级排序<br/>
 * 通过MyPriorityTransferQueue.transfer()方法放入其中的元素, 将等待消费者并阻塞, 一旦有消费者将优先被消费<br/>
 * MyPriorityTransferQueue.take()将优先消费transfered列表, transfered列表为空则则取PriorityBlockingQueue中的元素<br/>
 * @author lixiangke
 * @date 2017/11/28
 */
public class Main {
    public static void main(String[] args) throws InterruptedException {
        MyPriorityTransferQueue<Event> buffer = new MyPriorityTransferQueue<>();
        Producer producer = new Producer(buffer);
        Thread[] producerThreads = new Thread[10];
        for (int i = 0; i < producerThreads.length; i++) {
            producerThreads[i] = new Thread(producer);
            producerThreads[i].start();
        }

        Consumer consumer = new Consumer(buffer);
        Thread consumerThread = new Thread(consumer);
        consumerThread.start();
        System.out.printf("Main: Buffer : Consumer count : %d\n", buffer.getWaitingConsumerCount());

        Event myEvent = new Event("Core Event", 0);
        buffer.transfer(myEvent);
        System.out.printf("Main: My event has been transfered.\n");

        for (int i = 0; i < producerThreads.length; i++) {
            producerThreads[i].join();
        }

        TimeUnit.SECONDS.sleep(1);
        System.out.printf("Main: Buffer: Consumer count: %d\n", buffer.getWaitingConsumerCount());
        myEvent = new Event("Core Event 2", 0);
        buffer.transfer(myEvent);

        consumerThread.join();
        System.out.println("Main: End of the program.");
    }
}
